package traditional.thread.communicate;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 完全复制张孝祥的思路
 * 经过思考后发现：如果不用wait notify,也不用condition,事实上main方法是不会将cpu控制权交出去的，它会一直在搞，这样
 * 虽然实现了互斥，但是不会你一下我一下了
 * @author Germmy
 *
 */
public class TraditionalTheadLockTestZxxWithoutCommunicate {

	

	public static void main(String[] args) {

		final TraditionalTheadLockTestZxxWithoutCommunicate ttc = new TraditionalTheadLockTestZxxWithoutCommunicate();

		final Business business=new Business();
		
		// 整体循环50次
		for (int i = 0; i < 50; i++) {

			new Thread(new Runnable() {

				public void run() {
					// 大哥来搞100次
					business.main();

				}
			}).start();

			new Thread(new Runnable() {

				public void run() {
					// 小弟来搞10次
					business.sub();

				}
			}).start();

			System.out.println("主循环次数:" + i);

		}

	}

	
	 
	 
	 static class Business{
		 boolean isShouldSub = true;
		 Lock lock=new ReentrantLock();
		 void main() {
			 	lock.lock();
				/*while (isShouldSub) {
					try {
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}*/
				for (int i = 0; i < 100; i++) {
					System.out.println("main:" + i);
				}
				isShouldSub = true;
				lock.unlock();
			}

			 void sub() {
				 lock.lock();
				/*while (!isShouldSub) {
					try {
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}	
				}*/
				for (int i = 0; i < 10; i++) {
					System.out.println("sub:" + i);
				}
				isShouldSub = false;
				lock.unlock();
			}
			 
	 }
	 
	 
	 
	 

}
